package com.htdz.service.impl;

import com.htdz.dao.ResourceMapper;
import com.htdz.dao.RoleMapper;
import com.htdz.dao.RoleResourceMapper;
import com.htdz.dao.UsersRoleMapper;
import com.htdz.entity.*;
import com.htdz.service.RoleService;
import com.htdz.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private UsersRoleMapper usersRoleMapper;
	@Autowired
	private RoleResourceMapper roleResourceMapper;

	@Override
	public List<Role> listRole(Role role, Integer pageNum) {
		Map map = BeanUtil.transBean2Map(role);
		return roleMapper.listBy(map);
	}

	@Override
	public List<Node> listRoleTree(Role role, Long grantUsersId) {
		Map map = BeanUtil.transBean2Map(role);
		List<Role> roleList = roleMapper.listBy(map);
		Map usersMap = new HashMap();
		if(grantUsersId == null) grantUsersId = 0L;
		usersMap.put("usersId",grantUsersId);
		List<UsersRole> usersRoleList = usersRoleMapper.listBy(usersMap);
		List<Node> nodeList = new ArrayList<Node>();
		for(Role re :roleList){
			Node  node = new Node();
			Boolean isChecked = false;
			for(UsersRole usersRole:usersRoleList){
				if(re.getRoleId() == usersRole.getRoleId()) isChecked = true;
			}
			node.setChecked(isChecked);
			node.setId(re.getRoleId());
			node.setName(re.getRoleName());
			node.setOpen(true);
			node.setpId(0);

			nodeList.add(node);
		}
		return nodeList;
	}

	@Override
	public void saveUsersRole(Long grantUsersId, String checkedIds) {
		usersRoleMapper.delete(grantUsersId);

		String[] ids = checkedIds.split(",");
		for(String id : ids){
			Map map = new HashMap();
			map.put("usersId",grantUsersId);
			map.put("roleId",id);
			usersRoleMapper.insert(map);
		}
	}

	@Override
	public void saveRole(String roleName) {
		Map map = new HashMap();
		map.put("roleName",roleName);
        roleMapper.insert(map);
	}

	@Override
	public void deleteRole(Long roleId) {
		roleMapper.delete(roleId);
		usersRoleMapper.deleteByRoleId(roleId);
		roleResourceMapper.delete(roleId);
	}
}
